package com.dshore.messagecenter.quartz.dataStat;

import java.util.ArrayList;
import java.util.List;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.dshore.messagecenter.dao.system.SysMessageLogDao;
import com.dshore.messagecenter.model.system.SysMessageLog;

/**
 * 读取消息日志并入库
 * @author DSHORE
 *
 */
@Component
public class MsgLogStat implements ApplicationRunner{

	@Autowired
	private AmqpTemplate amqpTemplate;
	
	@Autowired
	private ConnectionFactory connectionFactory;
	
	@Autowired
	private SysMessageLogDao sysMessageLogDao;
	
	// 消息队列接入消息日志队列
	@Value("${rabbitmq.log.queue.mq}")
	private String logQueueMq;
	
	// 消息队列接入消息日志队列
	@Value("${rabbitmq.log.queue.server}")
	private String logQueueServer;
	
	@Override
	public void run(ApplicationArguments args) {
		RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
		// 启动后判断消息日志队列是否存在，不存在则新建
		if (rabbitAdmin.getQueueProperties(logQueueServer) == null) {
			rabbitAdmin.declareQueue(new Queue(logQueueServer));
		}
	}
	
	/**
	 * 接收消息日志
	 */
	public void receiveMsgLog() {
		// 异常消息集合
		List<SysMessageLog> sysMessageLogs = new ArrayList<SysMessageLog>();
		
		// 每次调用取500条消息
		for (int i = 0; i < 500; i++) {
			// 循环读取
			Object obj = amqpTemplate.receiveAndConvert(logQueueMq);
			if (obj != null) {
				sysMessageLogs.add(JSON.parseObject(new String((byte[]) obj), SysMessageLog.class));
			} else {
				break;
			}
		}
		
		// 当集合中有数据时，进行保存
		if (sysMessageLogs.size() > 0) {
			sysMessageLogDao.add(sysMessageLogs);
		}
	}
}
